import Axios from 'axios';

const tokenHeaderKey = 'X-Token';
const tokenStorageKey = 'SPACE_USER_TOKEN';
const httpClient = Axios.create({
    timeout: 10 * 1000 // 请求超时时间
});

function getToken(): string | null {
    return localStorage.getItem(tokenStorageKey);
}

function isSuccessCode(code: number): boolean {
    return code >= 200 && code < 300;
}

httpClient.interceptors.request.use(function useUserToken(option) {
    const token = getToken();
    if (token) {
        option.headers[tokenHeaderKey] = token;
    }
    return option;
});

httpClient.interceptors.response.use(function checkHttpCode(res) {
    if (isSuccessCode(res.status)) {
        return res;
    }
    return Promise.reject(res);
});

export default httpClient;
